layui.config({
    base: '../lib/layui/lay/mymodules/'
}).extend({
    xmSelect: 'xm-select'
}).use(['xmSelect','element','form','table','layer'], function(){
    var $ = layui.jquery
        ,element = layui.element
        ,form = layui.form
        ,layer = layui.layer
        ,xmSelect = layui.xmSelect
        ,util = layui.util
        ,table = layui.table;
    var peopleAuthData = [];
    var url = window.location.host;

    initCommunities(); //小区列表
    var currentComId = "";
    function initCommunities(){
        $.get('/acsCommunity/listCommunities', {}, function (result) {
            if(result != null){
                if(result.resultContent != null){
                    var a$opt_html = "";
                    var i = 0;
                    $.each(result.resultContent, function (index, item) {
                        if(i === 0){
                            currentComId = item.ID;
                            renderTable(item.ID);
                        }
                        a$opt_html += "<option id='" + item.CODE + "' value='" + item.ID + "'>" + item.NAME + "</option>";
                        i++;
                    });
                    $("#communityLocation").empty().append(a$opt_html);
                    form.render('select');
                    listBuildingTree(currentComId);
                }
            }
        });
    }

    function listBuildingTree(companyId){
        $.get('/doorDevice/listBuildingTree',{companyId:companyId},function (res) {
            if(res){
                var communityList = res.communityList;
                var buildingMap = res.buildingMap;
                var curr = "";
                for(var i in communityList){
                    curr = communityList[0].id;
                }
                var buildingOptions = "<option value=''>全部</option>";
                var buildings = buildingMap ? buildingMap[curr] : null;
                for(var i in buildings){
                    buildingOptions += "<option value='" + buildings[i].id + "'>" + buildings[i].text + "</option>";
                }
                $("#buildingLocation").empty().append(buildingOptions);
                $("#areaId").empty().append(buildingOptions);
                form.render();
            }
        });
    }

    form.on('select(communityLocation)', function(data){
        listBuildingTree(data.value);
    });
    function renderTable(companyId){
        table.render({
            elem: '#oneTable',
            url:'/doorDevice/list',
            height: 'full-150',
            method: 'get',
            // cellMinWidth: 80,
            where: {
                companyId: companyId
            },
            // parseData: function(res){ //res 即为原始返回的数据
            //     return {
            //         "code": 0, //解析接口状态
            //         "msg": 'msg',
            //         "count": res.count,
            //         "data": res.data
            //     };
            //
            // },
            page: true,
            cols: [[
                {field: 'lockName', title: '门禁名称', align:'center'}
                ,{field: 'openState', title: '开门状态', align:'center',templet:function (d) {
                        if(d.openState){
                            var state = d.openState;
                            return '[' + parseOpenState(state[0]) + ',' + parseOpenState(state[1])+']';
                        }
                        return '-';
                    }}
                ,{field: 'openNumber', title: '今日开门次数', align:'center'}
                ,{field: 'onlineState', title: '在线状态', align:'center',templet:function (d) {
                        return parseOnlineState(d.onlineState);
                    }}
                ,{field: 'activated', title: '激活状态',align:'center',templet:function (d) {
                        return parseActiveState(d.activated);
                    }}
                ,{field: 'onlineTime', title: '在线、断线时间开始时间', sort: true,align:'center',templet:function (d) {
                        return formatTime(d.onlineTime,"yyyy-MM-dd hh:mm:ss");
                        // return util.toDateString(d.onlineTime,"yyyy-MM-dd HH:mm:ss")
                    }}
                ,{field: 'longitude', title: '经度',align:'center'}
                ,{field: 'latitude', title: '维度',align:'center'}
                ,{field: 'createTime', title: '创建时间', sort: true,align:'center',templet:function (d) {
                        return formatTime(d.createTime,"yyyy-MM-dd hh:mm:ss");
                        // return util.toDateString(d.createTime,"yyyy-MM-dd HH:mm:ss")
                    }}
                // ,{field: 'right', width:180, title: '操作', toolbar: '#barDemo', align:'center'}
            ]]
        });
    }

    table.on('toolbar(oneTable)', function(obj){
        if(obj.event === 'add'){
            $.get('/accessDevice/getBuilding',{type:'单元门口机'},function (res) {
                var data = res.resultContent;
                var item = '<option></option>';
                for(i in data){
                    item += "<option value='" + data[i].BLOCK_NAME + "'>" + data[i].BLOCK_NAME + "</option>";
                }
                $("#oneBuilding").empty().append(item);
                form.render();
            });
            document.getElementById("oneEditForm").reset();
            openDeviceForm('oneDevice','oneEdit','entrance',0);
        }
    });

    table.on('toolbar(threeTable)', function(obj){
        if(obj.event === 'add'){
            changeDevice("threeDevice","threeDeviceDiv","add")
            document.getElementById("threeEditForm").reset();
            openDeviceForm('threeDevice','threeEdit','indoor',0);
        }
    });
    table.on('toolbar(fourTable)', function(obj){
        if(obj.event === 'add'){
            changeDevice("fourDevice","fourDeviceDiv","add")
            document.getElementById("fourEditForm").reset();
            openDeviceForm('fourDevice','fourEdit','indoor',0);
        }
    });


    table.on('tool(oneTable)', function(obj){
        var data = obj.data;
        if(obj.event === 'edit'){
            $.get('/accessDevice/getPeople',{buildLoc:data.buildingLoc},function (res) {
                onePeopleAuth.update({
                    data:res.resultContent
                });
                $.get('/accessDevice/getBuilding',function (res) {
                    var build = res.resultContent;
                    var item = '<option></option>';
                    for(i in build){
                        if (build[i].BLOCK_NAME === data.buildingLoc || build[i].STATE === '0'){
                            item += "<option value='" + build[i].BLOCK_NAME + "'>" + build[i].BLOCK_NAME + "</option>";
                        }
                    }

                    $("#oneBuilding").empty().append(item);
                    changeDevice("oneDevice","oneDeviceDiv","edit");
                    form.val('oneEditForm',{
                        "id":data.id,
                        "deviceId":data.deviceId,
                        "deviceName":data.deviceName,
                        "description":data.description,
                        "buildingLoc":data.buildingLoc,
                        "callNumber":data.callNumber,
                    });
                    if (data.auth != null){
                        oneAuth.setValue(data.auth.split(','));
                    }else {
                        oneAuth.setValue([]);
                    }
                    if (data.userInfo != null){
                        onePeopleAuth.setValue(data.userInfo.split(','));
                    }
                    form.render();
                    layer.open({
                        type: 1
                        ,title: '编辑'
                        ,area: ['40%', '100%']
                        ,maxmin: true
                        ,content: $("#oneEdit")
                    });
                });

            });

        }else if (obj.event === 'del'){
            $.get('/accessDevice/deleteDevice',{id:data.id},function (res) {
                layer.msg(res.resultDesc,{time:500,end:function () {
                        table.reload('oneTable');
                    }});
            })
        }
    });

    table.on('tool(threeTable)', function(obj){
        var data = obj.data;
        if(obj.event === 'edit'){
            changeDevice("threeDevice","threeDeviceDiv","edit")
            $.get('/accessDevice/getRoom',{buildLoc:data.buildingLoc},function (res) {
                var resData = res.resultContent;
                var item ='<option></option>';
                for(i in resData){
                    item += "<option value='" + resData[i].ROOM_ID + "'>" + resData[i].ROOM_NAME + "</option>";
                }
                $("#threeRoom").empty().append(item);
                form.val('threeEditForm',{
                    "id":data.id,
                    "deviceId":data.deviceId,
                    "deviceName":data.deviceName,
                    "description":data.description,
                    "roomLoc":data.roomLoc,
                    "buildingLoc":data.buildingLoc,
                    "monitoring":data.monitoring,
                    "callNumber":data.callNumber,
                });
                form.render();
                layer.open({
                    type: 1
                    ,title: '编辑'
                    ,area: ['40%', '100%']
                    ,maxmin: true
                    ,content: $("#threeEdit")
                });
            });

        }else if (obj.event === 'del'){
            $.get('/accessDevice/deleteDevice',{id:data.id},function (res) {
                layer.msg(res.resultDesc,{time:500,end:function () {
                        table.reload('threeTable');
                    }});
            })
        }
    });
    table.on('tool(fourTable)', function(obj){
        var data = obj.data;
        if(obj.event === 'edit'){
            changeDevice("fourDevice","fourDeviceDiv","edit")
            $.get('/accessDevice/getRoom',{buildLoc:data.buildingLoc},function (res) {
                var resData = res.resultContent;
                var item ='<option></option>';
                for(i in resData){
                    item += "<option value='" + resData[i].ROOM_ID + "'>" + resData[i].ROOM_NAME + "</option>";
                }
                $("#fourRoom").empty().append(item);
                form.val('fourEditForm',{
                    "id":data.id,
                    "deviceId":data.deviceId,
                    "deviceName":data.deviceName,
                    "description":data.description,
                    // "callOrder":data.callOrder,
                    "roomLoc":data.roomLoc,
                    "buildingLoc":data.buildingLoc,
                    "monitoring":data.monitoring,
                    "callNumber":data.callNumber,
                });
                form.render();
                layer.open({
                    type: 1
                    ,title: '编辑'
                    ,area: ['40%', '100%']
                    ,maxmin: true
                    ,content: $("#fourEdit")
                });
            });
        }else if (obj.event === 'del'){
            $.get('/accessDevice/deleteDevice',{id:data.id},function (res) {
                layer.msg(res.resultDesc,{time:500,end:function () {
                        table.reload('fourTable');
                    }});
            })
        }
    });

    form.on('submit(oneSubmit)',function(data){
        layer.confirm('是否确认提交？', {
            btn: ['确认', '返回']
        }, function () {
            data.field.companyId = $("#communityLocation").val();
            $.post('/doorDevice/gateLock/init',data.field,function (res) {
                if(res.resultCode === "000"){
                    layer.closeAll();
                    layer.msg('提交成功',{
                        time:500,
                        end:function () {
                            reloadOne();
                        }
                    });
                }else{
                    layer.msg(res.resultDesc,{icon:5});
                }
            });
        });
        return false;
    });
    form.on('submit(twoSubmit)',function(){
        let data = $("#twoEditForm").serialize()+'&monitoring='+url;
        var index = layer.load(1);
        if(twoPeopleAuth.getValue().length === 0){
            layer.msg('请选择人员信息!',{time:500});
            layer.close(index);
            return false;
        }

        return false;
    });
    form.on('submit(threeSubmit)',function(){
        let data = $("#threeEditForm").serialize()+'&userInfo='+url;
        var index = layer.load(1);
        $.post('/accessDevice/saveDevice',data,function (res) {
            layer.close(index);
            layer.msg(res.resultDesc,{time:500,end:function () {
                    layer.closeAll();
                    table.reload('threeTable');
                }});
        });
        return false;
    });
    form.on('submit(fourSubmit)',function(){
        let data = $("#fourEditForm").serialize()+'&userInfo='+url;
        var index = layer.load(1);
        $.post('/accessDevice/saveDevice',data,function (res) {
            layer.close(index);
            layer.msg(res.resultDesc,{time:500,end:function () {
                    layer.closeAll();
                    table.reload('fourTable');
                }});
        });
        return false;
    });

    form.on('submit(oneQuery)',function () {
        reloadOne();
        return false;
    });

    form.on('submit(threeQuery)',function () {
        var roomLoc = $("#threeQueryRoom").val();
        var deviceName = $("#threeDeviceName").val();
        table.reload('threeTable',{
            where:{roomLoc:roomLoc,deviceName:deviceName}
        });
        return false;
    });
    form.on('submit(fourQuery)',function () {
        var roomLoc = $("#fourQueryRoom").val();
        var deviceName = $("#fourDeviceName").val();
        table.reload('fourTable',{
            where:{roomLoc:roomLoc,deviceName:deviceName}
        });
        return false;
    });
    function reloadOne() {
        var searchField= $("#searchField").val();
        var searchString= $.trim($("#searchString").val());
        var lockIds= $("#buildingLocation").val();
        var lockState= $("#lockState").val();
        // var openType= $("#openType").val();

        table.reload('oneTable',{
            where:{"lockIds":lockIds,"lockState":lockState,"searchField":searchField,
                "searchString":searchString,companyId:$("#communityLocation").val()}
        });
    }

    reloadThree = function () {
        table.reload('threeTable',{
            where:{deviceName:'',buildingLoc:'',roomLoc:''}
        });
    };
    reloadFour = function () {
        table.reload('fourTable',{
            where:{deviceName:'',buildingLoc:'',roomLoc:''}
        });
    };

    // flushDevice = function () {
    //     reloadOne();
    // }

    changeDevice = function(inputId,divId,type){
        var item ;
        if (type === 'edit'){
            item = `<p style="margin-left: 9px;margin-top: 10px">设备MAC:</p>`
            item += '<input name="deviceId" readonly class="layui-input"/>'
        }else {
            item = `<p style="margin-left: 9px;margin-top: 10px">请选择当前创建所对应的系统设备:</p>`
            item += `<select id=${inputId} name="deviceId" lay-verify="required" ></select>`
        }
        $("#"+divId).empty().html(item);
    }

    openDeviceForm = function (inputName,formName,type,deviceId) {
        $.get('/accessDevice/getDevice',{type:type},function (res) {
            var data = res.resultContent;
            var item = '<option></option>';
            for(i in data){
                if (deviceId === data[i].DEVICE_MAC){
                    item += "<option selected value='" + data[i].DEVICE_MAC + "'>" + data[i].DEVICE_NAME +"("+data[i].DEVICE_MAC+")"+ "</option>";
                }else {
                    item += "<option value='" + data[i].DEVICE_MAC + "'>" + data[i].DEVICE_NAME +"("+data[i].DEVICE_MAC+")"+ "</option>";
                }
            }
            $("#"+inputName).empty().append(item);
            form.render();
            layer.open({
                type: 1
                ,title: '添加'
                ,area: ['40%', '100%']
                ,maxmin: true
                ,content: $("#"+formName)
            });
        });
    }

});

function parseOpenState(state) {
    switch (state) {
        case 0: return '关';
        case 1: return '开';
        default: return '-';
    }
}
function parseOnlineState(state) {
    switch (state) {
        case 0: return '离线';
        case 1: return '在线';
        default: return '-';
    }
}
function parseActiveState(state) {
    switch (state) {
        case 0: return "未激活";
        case 1: return "已激活";
        default: return "-";
    }
}
function formatTime(datetime,fmt) {
    if (parseInt(datetime)==datetime) {
        if (datetime.length==10) {
            datetime=parseInt(datetime)*1000;
        } else if(datetime.length==13) {
            datetime=parseInt(datetime);
        }
    }
    datetime=new Date(datetime);
    var o = {
        "M+" : datetime.getMonth()+1,                 //月份
        "d+" : datetime.getDate(),                    //日
        "h+" : datetime.getHours(),                   //小时
        "m+" : datetime.getMinutes(),                 //分
        "s+" : datetime.getSeconds(),                 //秒
        "q+" : Math.floor((datetime.getMonth()+3)/3), //季度
        "S"  : datetime.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (datetime.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
}